<template>
  <div class="bg-white dark:bg-zinc-900 sticky top-0 left-0 z-10 duration-500">
    <ul
      ref="ulTarget"
      class="relative flex overflow-x-auto p-1 text-xs text-zinc-600 overflow-hidden"
    >
      <!-- 滑块 -->
      <li
        ref="sliderTarget"
        :style="sliderStyle"
        class="absolute h-[22px] bg-zinc-900 dark:bg-zinc-800 rounded-lg duration-200"
      ></li>
      <!-- 汉堡按钮 -->
      <li
        class="fixed top-0 right-[-1px] h-4 px-1 flex items-center bg-white dark:bg-zinc-900 z-20 shadow-l-white dark:shadow-l-zinc"
        @click="onShowPopup"
      >
        <z-svg-icon class="w-1.5 h-1.5" name="hamburger" />
      </li>
      <!-- items -->
      <li
        v-for="(item, index) in categorys"
        :key="item.id"
        class="shrink-0 px-1.5 py-0.5 z-10 duration-200 last:mr-4"
        :class="{ 'text-zinc-100': currentCategoryIndex === index }"
        :ref="setItemRef"
        @click="onItemClick(item)"
      >
        {{ item.name }}
      </li>
    </ul>
    <!-- popup -->
    <z-popup v-model="isVisible">
      <menu-vue @onItemSelect="onItemClick" />
    </z-popup>
  </div>
</template>

<script setup>
import { ref, onBeforeUpdate, watch } from 'vue'
import { useScroll } from '@vueuse/core'
import menuVue from '../../menu/index.vue'
import { useCategoryStore } from '@/store/modules/category'
import { useAppStore } from '@/store/modules/app'
import { storeToRefs } from 'pinia'

const useCategory = useCategoryStore()
const { categorys } = storeToRefs(useCategory)

const useApp = useAppStore()
const { currentCategoryIndex } = storeToRefs(useApp)

// 滑块样式
const sliderStyle = ref({
  transform: 'translateX(0px)',
  width: '48px'
})

// 存储item的元素
let itemRefs = []
const setItemRef = (el) => {
  if (el) {
    itemRefs.push(el)
  }
}

// 更新前清空itemRefs
onBeforeUpdate(() => {
  itemRefs = []
})

// 获取ul的元素
const ulTarget = ref(null)

// 通过vueuse的useScroll监听ul的滚动
const { x: ulScrollLeft } = useScroll(ulTarget)

// 监听ul的滚动
watch(currentCategoryIndex, (val) => {
  const { left, width } = itemRefs[val].getBoundingClientRect()
  sliderStyle.value = {
    transform: `translateX(${ulScrollLeft.value + left - 10}px)`,
    width: `${width}px`
  }
})
// item点击
const onItemClick = (item) => {
  useApp.changeCategory(item)
  isVisible.value = false
}
// 控制popup的显示
const isVisible = ref(false)
const onShowPopup = () => {
  isVisible.value = !isVisible.value
}
</script>

<style lang="scss" scoped></style>
